import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_SCREENLOCKED } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';
import { PageEnum } from '@/enums/pageEnum';

import { getCurrentUserInfo, login } from '@/api/base/index';
import {storage} from '@/utils/Storage';
import { DictValueInfo, getDictValueAll } from '@/api/system/dict';
import {getIntegralSetting} from "@/api/course";
import {useCourse} from "@/store/modules/course";

export type UserInfoType = {
  // TODO: add your own data
  username: string;
  phone: string;
  hidePhone: string;
  pic: string;
};

export interface IUserState {
  token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: UserInfoType;
  enumData: Object;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: sessionStorage.getItem(ACCESS_TOKEN) || '',
    username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
    enumData: {},
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
    getEnumData(): Object {
      return this.enumData;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    setDictData(data: DictValueInfo[]) {
      this.enumData = data;
    },
    // 登录
    async login(params: any) {
      const response = await login(params);
      const { token, expire } = response;
      sessionStorage.setItem(ACCESS_TOKEN, token);
      storage.set(IS_SCREENLOCKED, false);
      this.setToken(token);
      const result = await getCurrentUserInfo();
      return result;
    },

    // 获取用户信息
    async getInfo() {
      const result = await getCurrentUserInfo();
      if (result.phone === null) {
        window['$dialog'].warning({
          title: '提示',
          content: '用户信息错误，请重新登录!',
          positiveText: '确定',
          //negativeText: '取消',
          closable: false,
          maskClosable: false,
          onPositiveClick: () => {
            sessionStorage.removeItem(ACCESS_TOKEN);
            storage.remove(CURRENT_USER);
            window.location.reload();
            // window.location.href = PageEnum.BASE_LOGIN;
          },
          onNegativeClick: () => {},
        });
        return false;
      }
      result.hidePhone = result.phone.substring(0, 3) + '****' + result.phone.substring(7, 11);
      storage.set(CURRENT_USER, result);
      this.setUserInfo(result);
      // 设置所有标签（字典）数据
      const r1 = await getDictValueAll();
      this.setDictData(r1);
      // 设置积分配置
      const r2 = await getIntegralSetting();
      useCourse().setIntegralSettingData(r2);
      return result;
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      sessionStorage.removeItem(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
      window.location.reload();
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  return useUserStore(store);
}
